package com.xxlComments.job.executor.crawler.util;

import net.sf.json.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述: 解析json
 *
 * @author Pfly
 * @create 2018-12-22 16:50
 */
public class ElementUtil {



    /**
     * 根据Url 查询出json并解析
     * @param url
     * @return
     * @throws IOException
     */
    public static Element findElementByJson(String url) throws IOException {
        /*将url解析成字符串*/
        Connection.Response execute = Jsoup.connect(url).ignoreContentType(true).execute();
        String body = execute.body();

        /*将字符串转换成json格式*/
        JSONObject jsonObject = JSONObject.fromObject(body);
        //根据字符串中的KEY 得到BODY value
        String html = (String) jsonObject.get("body");
        //将body转换成Document文档
        Document parse = Jsoup.parse(html);
        Element elementBody = parse.body();
        return elementBody;
    }


    /**
     *  根据传入的elements 遍历出该对象元素的集合内容
     * @param element
     * @return
     */
    public static List<String> ergodicByHtml(Elements element){
       List<String> list = new ArrayList();
        for (Element element1 : element) {
            list.add(element1.html());
        }
        return list;
    }

    /**
     *  根据传入的elements 遍历出该对象元素的集合内容
     * @param element
     * @return
     */
    public static List ergodicByTimeHtml(Elements element) throws ParseException {
        List<String> list = new ArrayList();
        for (Element element1 : element) {
            list.add(UpdateTime.Format_time(element1.html()));
        }
        return list;
    }

    /**
     *  根据传入的elements 遍历出该对象元素的集合链接
     * @param element
     * @return
     */
    public static List ergodicByAttr(Elements element){
        List list = new ArrayList();
        for (Element element1 : element) {
            list.add(element1.attr("style"));
        }
        return list;
    }
}
